package com.tanchengjin.admin.controller;

import com.tanchengjin.admin.model.dao.AdminPermissionMapper;
import com.tanchengjin.admin.model.dao.AdminRolePermissionMapper;
import com.tanchengjin.admin.model.dto.administrators.AllocPermission;
import com.tanchengjin.admin.model.pojo.AdminPermission;
import com.tanchengjin.admin.service.AdminPermissionService;
import com.tanchengjin.admin.service.AdministratorService;
import com.tanchengjin.admin.utils.LayuiAdminServerResponse;
import com.tanchengjin.admin.utils.ServerResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tanchengjin
 */
@Controller
@RequestMapping("${app.admin.prefix}/administrators/permission")
public class AdminPermissionManagerController {
    private final static Logger logger = LoggerFactory.getLogger(AdminPermissionManagerController.class);

    @Autowired
    private AdminPermissionMapper adminPermissionMapper;

    @Autowired
    private AdminRolePermissionMapper adminRolePermissionMapper;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private AdministratorService administratorService;
    @Autowired
    private AdminPermissionService adminPermissionService;

    @Value("${app.admin.prefix}")
    private String adminPrefix;

    @GetMapping("/index")
    public String index() {
        return "/admin/administrators/permission/list";
    }

    @RequestMapping(value = "/list", method = {RequestMethod.GET})
    @ResponseBody
    public LayuiAdminServerResponse index(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "10") int limit, @RequestParam(value = "roleId", required = false) String roleId) {
//        PageHelper.startPage(page, limit);
        List<AdminPermission> adminPermissionList = adminPermissionService.list();
//        List<AdminPermission> adminPermissionList = adminPermissionMapper.getAll();
//        int count = adminPermissionMapper.count();
        logger.info("roleId is [{}]", roleId);
        return LayuiAdminServerResponse.responseWithSuccess(adminPermissionList, "0");
    }

    @RequestMapping(value = "/create", method = {RequestMethod.GET})
    public String create(Model model) {
        List<AdminPermission> permissionList = adminPermissionMapper.getAll();
        model.addAttribute("permissionList", permissionList);
        HttpMethod[] values = HttpMethod.values();
        model.addAttribute("httpMethod", values);

        List<Map<String, String>> routeByPrefix = getRouteByPrefix(adminPrefix);
        model.addAttribute("routeList", routeByPrefix);
        return "/admin/administrators/permission/add";
    }

    @RequestMapping(value = "", method = {RequestMethod.POST})
    @ResponseBody
    public ServerResponse store(AdminPermission adminPermission) {
//        boolean save = adminPermissionService.save(adminPermission);
//        int i = save ? 1 : 0;
        int i = adminPermissionMapper.insertSelective(adminPermission);
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailureMessage("创建失败请重试");
        }
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    @ResponseBody
    public ServerResponse<AdminPermission> show(@PathVariable int id) {
        AdminPermission adminPermission = adminPermissionMapper.selectByPrimaryKey(id);
        return ServerResponse.responseWithSuccess(adminPermission);
    }

    @RequestMapping(value = "/{id}/edit", method = {RequestMethod.GET})
    public String edit(Model view, @PathVariable(value = "id") int id) {
        //当前权限
        AdminPermission adminPermission = adminPermissionMapper.selectByPrimaryKey(id);
        view.addAttribute("adminPermission", adminPermission);

        //所有可用的请求方法
        HttpMethod[] values = HttpMethod.values();
        view.addAttribute("httpMethod", values);

        //获取所有的路由/bean
        List<Map<String, String>> routeByPrefix = getRouteByPrefix(adminPrefix);
        view.addAttribute("routeList", routeByPrefix);

        List<AdminPermission> permissionList = adminPermissionMapper.getAll();
        view.addAttribute("permissionList", permissionList);
        return "/admin/administrators/permission/edit";
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.PUT})
    @ResponseBody
    public ServerResponse update(AdminPermission adminPermission, @PathVariable("id") int id) {
        AdminPermission adminPermissionInDB = adminPermissionMapper.selectByPrimaryKey(id);
        if (adminPermissionInDB == null) {
            return ServerResponse.responseWithFailureMessage("用户不存在，请重试");
        }
        adminPermission.setId(id);

        int i = adminPermissionMapper.updateByPrimaryKeySelective(adminPermission);


        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailureMessage("更新失败，请重试");
        }
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseBody
    public ServerResponse destroy(@PathVariable(value = "id") int id) {

        int i = adminPermissionMapper.deleteByPrimaryKey(id);
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailureMessage("删除失败请重试");
        }
    }

    @RequestMapping(value = "/json")
    @ResponseBody
    public ServerResponse getJson() {
        List<Map<String, String>> routerList = getRouteByPrefix(adminPrefix);
        return ServerResponse.responseWithSuccess(routerList);
    }

    /**
     * 获取所有路由
     *
     * @return
     */
    private List<Map<String, String>> getRoute() {
        RequestMappingHandlerMapping mapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> map1 = new HashMap<String, String>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                map1.put("url", url);
            }
            // 类名
            map1.put("className", method.getMethod().getDeclaringClass().getName());
            // 方法名
            map1.put("method", method.getMethod().getName());
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                map1.put("type", requestMethod.toString());
            }

            list.add(map1);
        }
        return list;
    }

    public List<Map<String, String>> getRouteByPrefix(String prefix) {
        RequestMappingHandlerMapping mapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> map1 = new HashMap<String, String>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                if (url.startsWith(prefix)) {
                    int length = prefix.length();
                    map1.put("url", url.substring(length));
                    // 类名
//                    map1.put("className", method.getMethod().getDeclaringClass().getName());
                    // 方法名
//                    map1.put("method", method.getMethod().getName());
                    RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
                    for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                        map1.put("method", requestMethod.toString());
                    }

                    list.add(map1);
                }
            }
        }
        return list;
    }

    @RequestMapping(value = "/allocPermission", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<Object> allocPermission(@RequestBody @Validated AllocPermission permissionDTO) {
        int i = adminPermissionService.addPermissionByRoleId(permissionDTO.getRoleId(), permissionDTO.getMenuIds());
//        int i = administratorService.allocPermission(permissionDTO.getRoleId(), permissionDTO.getMenuIds());
        if (i <= 0) {
            return ServerResponse.responseWithFailureMessage("分配失败,请重试!");
        }
        return ServerResponse.responseWithSuccess();
    }

    @RequestMapping(value = "/selectTree")
    @ResponseBody
    public List<AdminPermission> selectTree() {
        return administratorService.getMenuTree();
    }
}
